import * as THREE from 'three';
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
// 引入gui.js库
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';

const scene = new THREE.Scene();

const width = window.innerWidth;
const height = window.innerHeight;

const geometry = new THREE.BoxGeometry(100, 100, 100);
const material = new THREE.MeshLambertMaterial({
    color: 0x00ffff,
    transparent: true,
    opacity: 0.5,
})

const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(10, 10, 10)
scene.add(mesh);


const controls = {
    isRotate: false,
}

const gui = new GUI();
gui.domElement.style.right = 0
gui.domElement.style.width = '400px'
const positionFolder = gui.addFolder('位置')
positionFolder.add(mesh.position, 'x', 0, 1000)
positionFolder.add(mesh.position, 'y', [0, 10, 20, 100, 500, 1000])
const zPositionFolder = positionFolder.addFolder('Z轴')
zPositionFolder.add(mesh.position, 'z', 0, 1000).name('Z轴')

const camera = new THREE.PerspectiveCamera(70, width / height, 1, 3000);
camera.position.set(500, 400, 300);
camera.lookAt(0, 0, 0);

const pointLight = new THREE.PointLight(0xffffff);
pointLight.decay = 0.0;
pointLight.intensity = 3;
pointLight.position.set(400, 800, 300);
scene.add(pointLight);

// 创建一个环境光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.1);
scene.add(ambientLight);

const colorFolder = gui.addFolder('光线')
colorFolder.add(ambientLight, 'intensity', 0, 1).name('环境光强度')
colorFolder.addColor(material, 'color').name('材质颜色').onChange((val) => {
    console.log('材质颜色：' + JSON.stringify(val))
})

gui.add(controls, 'isRotate').name('旋转模型')

gui.add(mesh.position, 'y', {
    '上': 300,
    '中': 10,
    '下': -300
}).name('Y轴位置')

const axesHelper = new THREE.AxesHelper(320);
scene.add(axesHelper);

// 创建一个 WebGL 渲染器
const renderer = new THREE.WebGLRenderer({
    antialias: true
});
renderer.setSize(width, height);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.render(scene, camera);

window.onresize = function () {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
}

// 循环渲染
const loopRender = () => {
    if (controls.isRotate) {
        mesh.rotateY(0.02)
        mesh.rotateX(0.01)
        mesh.rotateZ(0.02)
    }
    // 重新渲染
    renderer.render(scene, camera);
    // 循环执行 loopRender 函数
    requestAnimationFrame(loopRender)
}
loopRender()

// 添加相机控件控制器 OrbitControls
new OrbitControls(camera, renderer.domElement);

export const render = () => {
    const dom = document.getElementById('render-canvas');
    dom.appendChild(renderer.domElement);
}

